package com.autotau;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

import java.util.List;

public class AutoTauService extends Service
{
  public static final String ACTION_SERVICE = "com.autotau.MAIN";

  public static final String PREFS_NAME = "AutoTauPrefs";

  private static final int NOTIFICATION_ID = 1;

  private final String c_AccessPointName = "Public-TAU";

  private WifiManager m_WifiManager;

  private String m_Username;
  private String m_Password;
  private int m_AuthAttempts;


  @Override
  public void onCreate()
  {
    super.onCreate();

    loadPreferences();

    m_WifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    initializeWiFiListener();
  }

  @Override
  public IBinder onBind(Intent intent)
  {
    return null;
  }


  private void authenticate()
  {
    AuthManager.LoginStatus status = AuthManager.login(m_Username, m_Password, m_AuthAttempts);

    switch (status)
    {
      case Success:
        notifyStatus("Authenticated!");
        break;
      case Unreachable:
        notifyStatus("Connection Error!");
        break;
      case BadUsernameOrPassword:
        notifyStatus("Bad Username or Password.");
        break;
      case UnknownServerResponse:
        notifyStatus("Unknown Error.");
        break;
    }

    Log.i("AutoTau", "Auth status: " + status);
  }

  private void loadPreferences()
  {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    m_Username = settings.getString("username", "");
    m_Password = settings.getString("password", "");
    m_AuthAttempts = settings.getInt("authAttempts", 10);

    Log.i("AutoTau", "Loaded preferences");
  }

  private void notifyStatus(String status)
  {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    //int icon = R.drawable.notification_icon;
    CharSequence tickerText = status;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(R.drawable.icon, tickerText, when);

    CharSequence contentTitle = "AutoTau";
    CharSequence contentText = status;
    Intent notificationIntent = new Intent(this, AutoTauService.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, notification);
  }

  private void initializeWiFiListener()
  {
    Log.i("AutoTau", "Initializing WifiListener");

    m_WifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

    BroadcastReceiver wifiScanResultsReceiver = new BroadcastReceiver()
    {
      @Override
      public void onReceive(Context context, Intent intent)
      {
        /*if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
        {
          Log.i("AutoTau", "Received scan results");

          List<ScanResult> scanResults = m_WifiManager.getScanResults();
          for (ScanResult scanResult : scanResults)
          {
            if (scanResult.SSID.equalsIgnoreCase(c_AccessPointName))
            {
              Log.i("AutoTau", "Found AP");
              //associate();
            }
          }
        }
        else*/
        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
        {
          WifiInfo wifiInfo = m_WifiManager.getConnectionInfo();

          String ssid = wifiInfo.getSSID();
          NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

          if (ssid != null &&
              ssid.equals(c_AccessPointName) &&
              info != null &&
              info.isConnected())
          {
            Log.i("AutoTau", "Connected to " + c_AccessPointName);

            notifyStatus("Authenticating...");
            authenticate();
          }
        }
      }
    };

    registerReceiver(wifiScanResultsReceiver, intentFilter);
  }
}
